package com.purang.web.listener;

import com.purang.web.annotation.Permission;
import com.purang.web.bean.SecurityPermission;
import com.purang.web.bean.SecurityPermissionFactory;
import com.purang.web.utils.ScanClassUtil;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

public class PermissionInitialListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        String driverClassName = sce.getServletContext().getInitParameter("driver-class-name");
        String url = sce.getServletContext().getInitParameter("url");
        String username = sce.getServletContext().getInitParameter("username");
        String password = sce.getServletContext().getInitParameter("password");
        ServletContext servletContext = sce.getServletContext();
        try {
            Class.forName(driverClassName);
            Connection connection = DriverManager.getConnection(url, username, password);
            servletContext.setAttribute("mysqlConnection",connection);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Set<Class<?>> classes = ScanClassUtil.getClasses("com.purang.web.view");
        Map<String, List<SecurityPermission>> permissionMap = new HashMap<>();
        for (Class<?> aClass : classes) {
            Method[] methods = aClass.getDeclaredMethods();
            for (Method method : methods) {
                if (method.isAnnotationPresent(Permission.class)) {
                    Permission annotation = method.getAnnotation(Permission.class);
                    String[] value = annotation.value();
                    String uri = annotation.uri();
                    if (!"".equals(value) && value != null && uri.length() > 0) {
                        List<SecurityPermission> securityPermissionList = Arrays.stream(value).map(a -> SecurityPermissionFactory.getSecurityPermission(a)).collect(Collectors.toList());
                        permissionMap.put(uri,securityPermissionList);
                    }
                }
            }
        }
        servletContext.setAttribute("permissionMap",permissionMap);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        Connection connection = (Connection) sce.getServletContext().getAttribute("mysqlConnection");
        if(connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
